<!--
 * @description  : 实地核查方位图-添加位置-标距组件
 * @create       : 2024-7-30
-->

<template>
  <view class="content">
    <view :style="{ width: getContainerWidth(), height: getContainerHeight() }" id="container"></view>
    <view class="m-market">
      <view class="entity-list">
        <view class="entity" v-for="(item, index) in entityList" :key="index">
          <view class="title bold">
            <u-image class="cur-image min-width" width="16px" src="/static/market/new-location.png" mode="widthFix"></u-image>
            <view class="name">{{ curPositionName }}</view>
          </view>
          <view class="title bold width" :style="{ marginLeft: item.entityType === 'school' ? '-16rpx' : '-6rpx' }">
            <u-image
              :style="getTarImgstyle(item.entityType)"
              :width="item.entityType === 'school' ? '30px' : '21px'"
              :src="`/static/certificate/${item.entityType}_icon.svg`"
              mode="widthFix"
            ></u-image>
            <view class="name">{{ item.name }}</view>
          </view>
          <view class="line"></view>
          <view class="title">
            <view class="label">位置：</view>
            <view class="value">{{ item.address }}</view>
          </view>
          <view class="title">
            直线距离<view :class="['distance', 'bold', 'border']" @click="handleDistanceEdit(item.id)">{{ item.lineDistance }}</view
            >米
          </view>
        </view>
      </view>
    </view>
    <u-modal title="实际测量距离（米）" ref="uModal" v-model="distanceModalShow" show-cancel-button async-close @confirm="distanceModalConfirm">
      <view class="slot-content">
        <u-input type="number" placeholder="" v-model="distanceModalInfo.distance" :clearable="false"></u-input>
      </view>
    </u-modal>
  </view>
</template>

<script>
import { AMapMixin } from "@/common/AMapMixin.js";

export default {
  mixins: [AMapMixin],
  props: {
    location: {
      type: Array,
      default: () => {
        return [];
      }
    },
    entityList: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      curCords: null,
      // 当前地图上marker实例集合
      curMarkerMap: {},
      // 当前地图上线路实例
      curMapLineList: [],
      // 距离修改模态框
      distanceModalShow: false,
      distanceModalInfo: {}
    };
  },
  computed: {
    getTarImgstyle() {
      return type => {
        const flag = type === "school";
        return {
          marginRight: flag ? "10rpx" : "18rpx",
          marginTop: flag ? "-12rpx" : "",
          minWidth: flag ? "30px" : "21px"
        };
      };
    },
    // 当前位置名称
    curPositionName() {
      return this.$storage.get("curConfirmInfo").curPositionName;
    },
    // 底部数据栏高度
    bottomHeight() {
      const len = this.entityList.length;
      return len < 2 ? len * 145 + 46 : 340;
    }
  },
  created() {
    this.curCords = new AMap.LngLat(this.location[0], this.location[1]);
  },
  methods: {
    initAmap() {
      this.setMapInstance();
    },
    getContainerHeight() {
      let p = this.$u.sys().windowHeight - 44 - this.bottomHeight - this.$u.sys().statusBarHeight + "px";
      // #ifdef H5-DINGDING || H5-WECHAT
      p = this.$u.sys().windowHeight - this.bottomHeight - this.$u.sys().statusBarHeight + "px";
      // #endif
      return p;
    },
    getContainerWidth() {
      return this.$u.sys().windowWidth + "px";
    },
    setMapInstance() {
      if (!this.hasInited) return;
      this.amap = new AMap.Map("container", {
        center: this.curCords,
        showControlButton: true,
        zoom: 18
      });
      const _this = this;
      this.loadPlugin("AMap.ControlBar", function() {
        const controlBar = new AMap.ControlBar({
          position: {
            top: "10px",
            right: "10px"
          }
        });
        _this.amap.addControl(controlBar);
      });
      this.drawDefaultInstance();
      this.drawEntityInstance();
      this.drawLineInstance();
    },
    // 绘制地图上的默认实例 当前位置 & 区域
    drawDefaultInstance() {
      const curLocation = new AMap.Marker({
        title: "当前位置",
        icon: new AMap.Icon({
          size: new AMap.Size(20, 30),
          imageSize: new AMap.Size(20, 30),
          image: "static/market/new-location.png" // 大图地址
        }),
        position: this.curCords
      });
      curLocation.setMap(this.amap);
    },
    // 绘制零售户 | 学校
    drawEntityInstance() {
      // 绘制前先清除已绘制实例
      this.clearMarker();
      if (!this.entityList.length) {
        return;
      }
      this.entityList.forEach(item => {
        this.drawMarker(item);
      });
    },
    // 绘制marker
    drawMarker(entity) {
      const { name, id, entityType, longitude, latitude } = entity;
      const sizes = entityType === "school" ? [40, 50] : [30, 40];
      const option = {
        title: name,
        icon: new AMap.Icon({
          image: `static/certificate/${entityType}_icon.svg`,
          size: new AMap.Size(sizes[0], sizes[1]),
          imageSize: new AMap.Size(sizes[0], sizes[1])
        }),
        position: [longitude, latitude],
        extData: { id, entityType }
      };
      const marker = new AMap.Marker(option);
      marker.setMap(this.amap);
      this.curMarkerMap[id] = marker;
    },
    // 传marker实例则单清，否则全清
    clearMarker(instance) {
      if (instance) {
        instance.setMap(null);
        const idx = this.curPlotPointMarkers.findIndex(item => item.getExtData().id === instance.getExtData().id);
        this.curPlotPointMarkers.splice(idx, 1);
      } else {
        Object.keys(this.curMarkerMap).forEach(key => {
          this.curMarkerMap[key].setMap(null);
        });
        this.curMarkerMap = {};
      }
    },
    // 绘制线路
    async drawLineInstance() {
      // 绘制前先清除已绘制线路
      this.clearPolyline();
      if (!this.entityList.length) {
        return;
      }
      for (let i = 0; i < this.entityList.length; i++) {
        const item = this.entityList[i];
        // 辽宁特例-显示直线距离
        this.curMarkerMap[item.id].setLabel({
          direction: "right",
          content: `<view style="font-size: 14rpx; font-weight: bold">${item.name}<br /><view style="color: #f78e00">${item.lineDistance}米</view> </view>`
        });
        const paths = [];
        // 将起点与终点加入线路中
        paths.push([+this.location[0], +this.location[1]]);
        paths.push([+item.longitude, +item.latitude]);
        this.drawPolyline(paths, item);
      }
      // 根据步行导航距离排序
      this.entityList = this.entityList.sort((a, b) => a.lineDistance - b.lineDistance);
      // 距离最近路径差异化
      this.handleNearestEntity();
      // 自适应展示所有线路
      this.amap.setFitView(this.curMapLineList);
    },
    // 绘制线
    drawPolyline(paths, entity, isManual) {
      const option = {
        path: paths,
        isOutline: true,
        outlineColor: "#ffeeee",
        borderWeight: 2,
        strokeWeight: 5,
        strokeColor: "#0091ff",
        strokeOpacity: 0.9,
        lineJoin: "round",
        zIndex: 10,
        extData: { id: entity.id }
      };
      const polyLine = new AMap.Polyline(option);
      polyLine.setMap(this.amap);
      this.curMapLineList.push(polyLine);
    },
    handleNearestEntity() {
      const id = this.entityList[0].id;
      this.curMapLineList.forEach(line => {
        if (line.getExtData().id === id) {
          line.setOptions({
            strokeWeight: 7,
            strokeColor: "#FF6A71",
            zIndex: 11
          });
        }
      });
    },
    // 传polyLine实例则单清，否则全清
    clearPolyline(instance) {
      if (instance) {
        this.amap.remove(instance);
        const idx = this.allManualLineList.findIndex(item => item.getExtData().id === instance.getExtData().id);
        this.allManualLineList.splice(idx, 1);
      } else {
        this.amap.remove(this.curMapLineList);
        this.curMapLineList = [];
      }
    },
    // 编辑距离
    handleDistanceEdit(id) {
      const { lineDistance, name } = this.entityList.find(item => item.id === id);
      this.distanceModalInfo = {
        id,
        name,
        distance: lineDistance
      };
      this.distanceModalShow = true;
    },
    // 编辑距离提交
    distanceModalConfirm() {
      // 校验
      this.$refs.uModal.clearLoading();
      const { id, distance, name } = this.distanceModalInfo;
      if (+distance > 200) {
        uni.showToast({
          title: "距离不能大于200米",
          icon: "none"
        });
        return;
      }
      if (distance.slice(distance.indexOf(".")).length > 3) {
        uni.showToast({
          title: "距离最多保留两位小数",
          icon: "none"
        });
        return;
      }
      this.distanceModalShow = false;
      this.entityList.forEach(item => {
        if (item.id === id) {
          item.lineDistance = distance;
        }
      });
      // 刷新label显示距离
      this.curMarkerMap[id].setLabel({
        content: `<view style="font-size: 14rpx; font-weight: bold">${name}<br /><view style="color: #f78e00">${distance}米</view> </view>`
      });
    }
  }
};
</script>

<style lang="scss" scoped>
#container {
  /* #ifdef H5 */
  width: 100%;
  height: calc(100% - 30rpx);
  /* #endif */
  /* #ifdef APP-PLUS */
  height: calc(100vh - 44 - var(--status-bar-height));
  margin-top: calc(44 + var(--status-bar-height));
  /* #endif */
}

.slot-content {
  padding: 0 40rpx;
  .u-input {
    border: 1px solid;
    margin: 40rpx 0;
  }
}

.m-market {
  position: fixed;
  bottom: 120rpx;
  left: 0;
  right: 0;
  z-index: 999;
  background-color: #ffffff;
  padding: 0 30rpx;
  .entity-list {
    max-height: 540rpx;
    overflow-y: auto;
    .entity {
      padding: 20rpx;
      border-bottom: 1px solid #cecece;
      position: relative;
      .bold {
        font-weight: bold;
      }
      .line {
        height: 22rpx;
        border-left: 1px solid #666;
        position: absolute;
        top: 76rpx;
        left: 36rpx;
      }
      .title {
        color: #333333;
        display: flex;
        font-size: 26rpx;
        margin: 10rpx 0;
        position: relative;
      }
      .title:last-child {
        margin-top: 16rpx;
      }
      .cur-image {
        margin-right: 20rpx;
      }
      .min-width {
        min-width: 16px;
      }
      .name {
        line-height: 50rpx;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }
      .label {
        color: #666666;
        font-weight: 100;
        white-space: nowrap;
      }
      .value {
        font-weight: 400;
      }
      .distance {
        color: #f78e00;
        margin: 0 20rpx;
      }
      .border {
        border: 1px solid #c7c7c7;
        padding: 0 10rpx;
      }
    }
  }
}
</style>
